
module Beep_Module
(

	CLK_50M,RST_N,KEY,

	BEEP
);


input			CLK_50M;					
input			RST_N;					
input 	[ 7:0]	KEY;					
output			BEEP;					

reg		[15:0]	time_cnt;				
reg		[15:0]	time_cnt_n;				
reg		[15:0]	freq;					
reg		[15:0]	freq_n;				
reg				beep_reg;				
reg				beep_reg_n;				


always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)								
		time_cnt <= 16'b0;						
	else
		time_cnt <= time_cnt_n;			
end


always @ (*)
begin
	if(time_cnt == freq)						
		time_cnt_n = 16'b0;					
	else
		time_cnt_n = time_cnt + 1'b1;		

end


always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)								
		beep_reg <= 1'b0;					
	else
		beep_reg <= beep_reg_n;			
end


always @ (*)
begin
	if(time_cnt == freq)						
		beep_reg_n = ~beep_reg;			
	else
		beep_reg_n = beep_reg;			
end


always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)								
		freq <= 16'b0;							
	else	
		freq <= freq_n;						
end


always @ (*)
begin
	case(KEY)
		8'h30: freq_n = 16'd0;			
		8'h31: freq_n = 16'd47774; 	
		8'h32: freq_n = 16'd42568; 	
		8'h33: freq_n = 16'd37919; 	
		8'h34: freq_n = 16'd35791; 
		8'h35: freq_n = 16'd31888;
		8'h36: freq_n = 16'd28409; 
		8'h37: freq_n = 16'd25309; 
		8'h38: freq_n = 16'd23889; 
		8'h39: freq_n = 16'd21276; 
		default	  : freq_n = freq;
	endcase
end

assign BEEP = beep_reg;	

endmodule



